import os
import mindspore
from mindspore import nn
from mindspore.dataset import vision, transforms
from mindspore.dataset import MnistDataset

from download import download


class Network(nn.Cell):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.dense_relu_sequential = nn.SequentialCell(
            nn.Dense(28*28, 512),
            nn.ReLU(),
            nn.Dense(512, 512),
            nn.ReLU(),
            nn.Dense(512, 10)
        )

    def construct(self, x):
        x = self.flatten(x)
        logits = self.dense_relu_sequential(x)
        return logits



# 数据集下载函数，并返回数据集对象
def get_dataset(url):

    if os.path.exists('./MNIST_Data'):
        print("数据集已下载无需重复下载")

    else:
        path = download(url, "./", kind="zip", replace=True)

    train_dataset, test_dataset = MnistDataset('MNIST_Data/train'), MnistDataset('MNIST_Data/test')
    return train_dataset, test_dataset


def datapipe(dataset, batch_size):
    image_transforms = [
        vision.Rescale(1.0 / 255.0, 0),
        vision.Normalize(mean=(0.1307,), std=(0.3081,)),
        vision.HWC2CHW()
    ]
    label_transform = transforms.TypeCast(mindspore.int32)

    dataset = dataset.map(image_transforms, 'image')
    dataset = dataset.map(label_transform, 'label')
    dataset = dataset.batch(batch_size)
    return dataset

# 1. 正向计算过程
def forward_fn_model(model, loss_fn):
    def forward_fn(data, label):
        logits = model(data)
        loss = loss_fn(logits, label)
        return loss, logits
    return forward_fn


# 3. 定义一次训练
def train_step(data, label, grad_fn, optimizer):
    (loss, _), grads = grad_fn(data, label)
    optimizer(grads)
    return loss

# 定义训练函数
def train(model, dataset, grad_fn, optimizer):
    size = dataset.get_dataset_size()
    model.set_train()
    for batch, (data, label) in enumerate(dataset.create_tuple_iterator()):
        loss = train_step(data, label, grad_fn, optimizer)

        if batch % 100 == 0:
            loss, current = loss.asnumpy(), batch
            print(f"loss: {loss:>7f}  [{current:>3d}/{size:>3d}]")


def model_test(model, dataset, loss_fn):
    num_batches = dataset.get_dataset_size()
    model.set_train(False)
    total, test_loss, correct = 0, 0, 0
    for data, label in dataset.create_tuple_iterator():
        pred = model(data)
        total += len(data)
        test_loss += loss_fn(pred, label).asnumpy()
        correct += (pred.argmax(1) == label).asnumpy().sum()
    test_loss /= num_batches
    correct /= total
    print(f"Test: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")


def load_model():
    model = Network()

    # 加载模型参数
    param_dict = mindspore.load_checkpoint("model.ckpt")
    param_not_load, _ = mindspore.load_param_into_net(model, param_dict)
    print(param_not_load)

    model.set_train(False)

    return model


def model_predicted(model):
    # 数据集下载地址
    url = "https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/datasets/MNIST_Data.zip"
    train_dataset, test_dataset = get_dataset(url)
    test_dataset = datapipe(test_dataset, 64)

    model.set_train(False)
    for data, label in test_dataset:
        pred = model(data)
        predicted = pred.argmax(1)
        print(f'Predicted: "{predicted[:10]}", Actual: "{label[:10]}"')
        break


def main(epochs):
    # 数据集下载地址
    url = "https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/datasets/MNIST_Data.zip"
    train_dataset, test_dataset = get_dataset(url)
    train_dataset = datapipe(train_dataset, 64)
    test_dataset = datapipe(test_dataset, 64)

    # 定义模型
    model = Network()

    # 初始化损失函数和优化器
    loss_fn = nn.CrossEntropyLoss()
    optimizer = nn.SGD(model.trainable_params(), 1e-2)

    forward_fn = forward_fn_model(model, loss_fn)

    # 得到梯度函数
    grad_fn = mindspore.value_and_grad(forward_fn, None, optimizer.parameters, has_aux=True)

    for t in range(epochs):
        print(f"Epoch {t + 1}\n-------------------------------")
        train(model, train_dataset, grad_fn, optimizer)
        model_test(model, test_dataset, loss_fn)

    # Save checkpoint
    mindspore.save_checkpoint(model, "model.ckpt")
    print("保存模型参数到 model.ckpt")


def show_dataset_col():
    # 数据集下载地址
    url = "https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/datasets/MNIST_Data.zip"
    train_dataset, test_dataset = get_dataset(url)
    print(train_dataset.get_col_names())

def show_shape():
    url = "https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/datasets/MNIST_Data.zip"
    train_dataset, test_dataset = get_dataset(url)

    test_dataset = datapipe(test_dataset, 64)
    for image, label in test_dataset.create_tuple_iterator():
        print(f"Shape of image [N, C, H, W]: {image.shape} {image.dtype}")
        print(f"Shape of label: {label.shape} {label.dtype}")
        break

    for data in test_dataset.create_dict_iterator():
        print(f"Shape of image [N, C, H, W]: {data['image'].shape} {data['image'].dtype}")
        print(f"Shape of label: {data['label'].shape} {data['label'].dtype}")
        break

def show_model():
    model = Network()
    print(model)


if __name__ == '__main__':
    main(3)
    model = load_model()
    model_predicted(model)
    # show_model()
